<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-03-30 14:24:19
 * @LastEditTime: 2024-04-06 19:19:08
 * @FilePath: \env-manager-pc\src\views\system\role\edit.vue
-->
<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { useInitForm, useRules } from './page'
import type { ModelOpen } from '@/types/page'
import { ModelType } from '@/types/common'
import userApi from '@/api/modules/user'

const emits = defineEmits(['submit'])

// const userStore = useUserStore()
const dialogVisible = ref(false)
const { formData, initForm } = useInitForm()
const formRef = ref<FormInstance>()
const btnLoading = ref(false)
const modelType = ref(ModelType.add)
const roleTreeList = ref<any[]>([])
const loading = ref(false)

const rules = useRules()

const treeRef = ref<any>({})
function setComponentRef(el: any, item: any) {
  treeRef.value[item.Code] = el
}

function getRoleAuth(roleId: string) {
  loading.value = true
  userApi.GetRolePopedoms({ roleObjID: roleId }).then((res: any) => {
    Object.keys(res).forEach((key) => {
      treeRef.value[key] && treeRef.value[key].setCheckedKeys(res[key])
    })
    loading.value = false
  }, () => {
    loading.value = false
  })
}

function open(options: ModelOpen) {
  modelType.value = options.type
  if (options.data) {
    formData.value = { ...options.data }
    nextTick(() => {
      getRoleAuth(options.data.ObjID)
    })
  }
  dialogVisible.value = true
}

const isEdit = computed(() => modelType.value === ModelType.edit)

function doLoading(flag: boolean) {
  btnLoading.value = flag
}

function submit() {
  formRef.value?.validate((vaild) => {
    if (vaild) {
      const data: any = { ...formData.value }
      data.Popedoms = {}
      Object.keys(treeRef.value).forEach((key) => {
        data.Popedoms[key] = treeRef.value[key].getCheckedKeys()
      })
      emits('submit', data, doLoading)
    }
  })
}

async function getRolePopedoms() {
  try {
    const res = await userApi.GetPopedoms()
    roleTreeList.value = res.map((item: any) => ([{ ...item, Children: item.Popedoms }]))
  }
  catch (err) {
    doLoading(false)
  }
}
getRolePopedoms()

function close() {
  dialogVisible.value = false
  btnLoading.value = false
  initForm()
  Object.keys(treeRef.value).forEach((key) => {
    treeRef.value[key].setCheckedKeys([])
  })
}

const defaultProps = {
  children: 'Children',
  label: 'Name',
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    title="角色编辑"
    width="80%"
    top="1%"
    draggable
    @closed="close"
  >
    <div class="max-h-[65vh] w-full overflow-x-hidden overflow-y-auto">
      <ElForm ref="formRef" label-width="180px" label-position="top" label-suffix="：" :model="formData" :rules="rules">
        <ElRow :gutter="30">
          <ElCol :span="12">
            <ElFormItem label="角色" prop="Name">
              <ElInput v-model="formData.Name" :disabled="isEdit" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="备注" prop="Remark">
              <ElInput v-model="formData.Remark" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <el-tree
              v-for="(item, index) in roleTreeList"
              :ref="(el:any) => setComponentRef(el, item[0])"
              :key="index"
              :data="item"
              show-checkbox
              node-key="Code"
              highlight-current
              :props="defaultProps"
            >
              <template #default="{ data }">
                <span :title="data.Description">{{ data.Name }}</span>
              </template>
            </el-tree>
          </ElCol>
        </ElRow>
      </ElForm>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
